import {Rule} from "antd/es/form";
import React from "react";
import {Res} from "@/api/objects";
import UserApi from "@/api/web/UserApi.ts";
import {Button, Form, Input, Tabs} from "antd";
import useUserStore from "@/store/UserStore.ts";
import {useNavigate} from "react-router";
import {createStyles} from "antd-style";

const usernameRule: Rule = {
    type: "string",
    required: true,
    min: 5,
}

const passwordRule: Rule = {
    type: "string",
    required: true,
    min: 5,
}

const LoginForm: React.FC<{ afterSubmit: (res: Res<string>) => void }> = ({afterSubmit}) => {
    const onSubmit = (formData: { username: string, password: string }) => {
        UserApi.login(formData.username, formData.password)
            .then(afterSubmit)
    }

    return (
        <Form
            name="login"
            labelCol={{flex: '100px'}}
            labelAlign="right"
            wrapperCol={{flex: 1}}
            colon={false}
            scrollToFirstError
            onFinish={(values) => {
                onSubmit(values)
            }}
        >
            <Form.Item label="用户名"
                       name="username"
                       rules={[usernameRule]}>
                <Input/>
            </Form.Item>
            <Form.Item label="密码"
                       name="password"
                       rules={[passwordRule]}>
                <Input.Password/>
            </Form.Item>
            <Form.Item label=" ">
                <Button type="primary" htmlType="submit">
                    登录
                </Button>
            </Form.Item>
        </Form>
    )
}

const CreateUserFrom: React.FC<{ afterSubmit: (res: Res<string>) => void }> = ({afterSubmit}) => {
    const onSubmit = (formData: { username: string, password: string }) => {
        const {username, password} = formData;
        UserApi.createUser(username, password).then(afterSubmit)
    }

    return (
        <Form
            name="create"
            labelCol={{flex: '100px'}}
            labelAlign="right"
            wrapperCol={{flex: 1}}
            colon={false}
            scrollToFirstError
            onFinish={(values) => {
                onSubmit(values)
            }}
        >
            <Form.Item label="用户名"
                       name="username"
                       rules={[usernameRule]}>
                <Input/>
            </Form.Item>
            <Form.Item label="密码"
                       name="password"
                       rules={[passwordRule]}>
                <Input.Password/>
            </Form.Item>
            <Form.Item label="确认密码"
                       name="password2"
                       rules={[passwordRule,
                           (config) => ({
                               validator: (_, value) => {
                                   const pwd1 = config.getFieldValue("password");
                                   if (pwd1 && pwd1 == value) {
                                       return Promise.resolve()
                                   }
                                   return Promise.reject(
                                       new Error("两次输入的密码不相同"),
                                   )
                               },
                           }),
                       ]}>
                <Input.Password/>
            </Form.Item>
            <Form.Item label=" ">
                <Button type="primary" htmlType="submit">
                    创建用户
                </Button>
            </Form.Item>
        </Form>
    )
}

const useStyles = createStyles(({css, token}) => {
    return {
        formContainer: css`
            
        `,
    }
})

export default () => {
    const styles = useStyles().styles;
    const userStore = useUserStore();
    const navigate = useNavigate();

    /**
     * 表单提交完成后处理
     */
    const afterSubmit = () => {
        UserApi.getSelf().then((res) => {
            userStore.setUser(res.data)
            window.messageApi.success("登录成功").then()
            navigate("/home")
        })
    }

    return (
        <div className={styles.formContainer}>
            <div className="content">
                <Tabs
                    type="line"
                    animated
                    items={[
                        {
                            label: "用户登录",
                            key: '0',
                            children: <LoginForm afterSubmit={afterSubmit}/>,
                        },
                        {
                            label: "创建用户",
                            key: '1',
                            children: <CreateUserFrom afterSubmit={afterSubmit}/>,
                        },
                    ]}
                />
            </div>
        </div>
    )
}
